/*数据校验*/
const jason_validator = require('../../utils/jason_validator');
/*token校验*/
const token_vilidate = require('./controller_tool/token_vilidate');
/*数据库操作*/
const basics_db = require('../dbhelper/basics_db');

/**
 * 创建活动 执行插入
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.establishActivities = async(ctx, next) => {
  /*参数声明*/
  let body = ctx.request.body;
  //整理数据，验证数据有效性
  let data  = {};
  let insertData = {};
  for(let i = 0;i<body.length;i++)
  {
    data = {};
    data.id = body[i].id;
    data.sid = body[i].sid;
    data.title = body[i].title;
    data.describe = body[i].describe;
    data.detail = body[i].detail;
    data.attach = body[i].attach;
    data.price = body[i].price;
    data.startTime = body[i].startTime;
    data.endTime = body[i].endTime;
    data.createTime = new Date();

    
    /*数据操作*/
    insertData = await basics_db.insert('activities', body);
  }

  /*逻辑分支*/
    if(insertData.result.ok === 1) {
      return ctx.body = {
        statusText: '创建成功',
        status: 'success'
      }
    } else {
      return ctx.body = {
        statusText: '创建失败',
        status: 'error'
      }
    }
}

/**
 * 活动报名 执行查询-插入-更新
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.activitiesSignUp = async(ctx, next) => {
  /*参数声明*/
  let body = ctx.request.body;
  let openid = body.openid;
  /*数据操作*/
  let data = await basics_db.findOne('user', {openid})

  /*逻辑处理*/
  if(data) {
    if (data.signActive.includes(body.activitiesId)) {
    	return ctx.body = {
        statusText: '该微信已存在报名信息！',
        status: 'error'
      }
    }else{
      return ctx.body = {
        statusText: '不是同一活动 应修改数据！',
        status: 'tes'
      }
    }
    
  } else {
    /*补充数据 报名时间*/
    body.timeStamp = new Date().getTime()
    /*补充数据 活动列表*/
    body.signActive = []
    body.signActive.push(body.activitiesId)
    /*数据操作*/
    let insertData = await basics_db.insert('user', body)
    /*逻辑分支*/
    if(insertData.result.ok === 1) {
      return ctx.body = {
        statusText: '报名成功',
        status: 'success'
      }
    } else {
      return ctx.body = {
        statusText: '注册失败',
        status: 'error'
      }
    }
  }
}

